<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="Connect.*" %>
<%@include file="restrict_to_not_logged_in.jsp"%>

<%
	// Retrieve the submitted information.
	String username = request.getParameter("username");
	String password = request.getParameter("password");

	// Getting information and updating the database.
	java.sql.Connection conn = null;
	try {
		// Connect to the database.
		Class.forName(ConnectionInfo.myJDBCDriver()).newInstance();
		java.util.Properties sysprops = System.getProperties();
		sysprops.put("user", ConnectionInfo.myUserID());
		sysprops.put("password", ConnectionInfo.myPassword());
		conn = java.sql.DriverManager.getConnection(ConnectionInfo.myURL(), sysprops);

		// Check if the requested username and password combination exists.
		java.sql.Statement statement = conn.createStatement();
		java.sql.ResultSet rs = statement.executeQuery("SELECT username FROM users WHERE username = '" + username + "' AND password = '"
				+ password + "'");
		String errors = "";
		if (rs.next()) {
			// Login credentials are valid. Check what type of user it is.
			rs = statement.executeQuery("SELECT level FROM employees WHERE username = '" + username + "'");
			if (rs.next()) {
				// The user is either an employee or manager.
				int level = rs.getInt(1);
				if (level == 0) {
					// Mark the user as a manager.
					session.setAttribute("user_type", "0");
				} else {
					// Mark the user as an employee.
					session.setAttribute("user_type", "1");
				}
			} else {
				// Mark the user as a customer.
				session.setAttribute("user_type", "2");
			}
			// Mark the user as logged in and redirect to the home page.
			session.setAttribute("logged_user", username);
			response.sendRedirect("index.jsp");
		} else {
			errors = "* Invalid username and password combination.";
		}

		// Redirect to login page if there were any errors.
		if (!errors.equals("")) {
			// Record the user submitted data.
			session.setAttribute("login_errors", errors);
			session.setAttribute("username", username);
			response.sendRedirect("login.jsp");
		}
	} catch (Exception e) {
		e.printStackTrace();
		out.print(e.toString());
	} finally {
		try {
			conn.close();
		} catch (Exception ee) {
		}
	}
%>